<?php
class Default_Model_TinTucMapper {

	protected $_dbTable;
	protected $db;

	public function setDbTable($dbTable) {
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable() {
		if (null === $this->_dbTable) {
			$this->setDbTable('Default_Model_DbTable_TinTuc');
		}
		return $this->_dbTable;
	}

	public function getDb(){
		if ($this->db === null) {
			$this->db = Zend_Registry::get('connectDB');
		}
		return $this->db;
	}
	/*
	 *countItem
	 */

	public function countItem() {
		$table = $this->getDbTable();
		$select = $table->select();
		$select->from($table, array("count(id) as totalItem"));
		$resultSet = $table->fetchAll($select);
		$array = $resultSet->toArray();
		return $array[0]['totalItem'];
	}
	
	/*
	 * fetch
	 */
	public function fetchBy($condition = null, $orderBy = null, $page = 0, $pageSize = 0, $option = 'view') {
		$table = $this->getDbTable();
		$select = $table->select();
		$select->from($table);

		if ($condition != null) {
			$select->where($condition);
		}

		if ($pageSize > 0) {
			$select->limitPage($page, $pageSize);
		}

		if ($orderBy != null) {
			$orderedColumns = array();
			
			foreach ($orderBy as $val) {
				array_push($orderedColumns, $val['colName'] . ' ' . $val['order']);
			}

			$select->order($orderedColumns);
		}

		$resultSet = $this->getDbTable()->fetchAll($select);
		return $this->processResultSet($resultSet->toArray(), $option);
	}

	/*
	 *processResultSet
	 */
	private function processResultSet($resultSet, $option = 'view') {
		$entries = "";
		if($option == 'view') {
			foreach ($resultSet as $row) {
				$entries = new Default_Model_TableColumn_TinTuc($row);
			}
		} else {
			$entries = array();
			foreach ($resultSet as $row) {
				$entry = new Default_Model_TableColumn_TinTuc($row);
				$entries[] = $entry;
			}
		}
		return $entries;
	}
	
	/*
	 * change item
	 */
	public function change($id, $data = null) {
		$where = 'id IN (' . $id . ')';
		$this->getDbTable()->update($data, $where);
	}
}